package cn.iocoder.yudao.module.trade.service.delivery;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.pickup.DeliveryPickUpStoreCreateReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.pickup.DeliveryPickUpStorePageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.delivery.vo.pickup.DeliveryPickUpStoreUpdateReqVO;
import cn.iocoder.yudao.module.trade.controller.app.delivery.vo.pickup.AppDeliveryPickUpStoreRespVO;
import cn.iocoder.yudao.module.trade.convert.delivery.DeliveryPickUpStoreConvert;
import cn.iocoder.yudao.module.trade.convert.storeimage.DeliveryPickUpStoreImageConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.delivery.DeliveryPickUpStoreDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.deliverypickupstoreimage.DeliveryPickUpStoreImageDO;
import cn.iocoder.yudao.module.trade.dal.mysql.delivery.DeliveryPickUpStoreMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.deliverypickupstoreimage.DeliveryPickUpStoreImageMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.PICK_UP_STORE_NOT_EXISTS;

/**
 * 自提门店 Service 实现类
 *
 * @author jason
 */
@Service
public class DeliveryPickUpStoreServiceImpl implements DeliveryPickUpStoreService {

    @Resource
    private DeliveryPickUpStoreMapper deliveryPickUpStoreMapper;

    @Resource
    private DeliveryPickUpStoreImageMapper deliveryPickUpStoreImageMapper;

    @Resource
    private DeptApi deptApi;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createDeliveryPickUpStore(DeliveryPickUpStoreCreateReqVO createReqVO) {
        // 插入部门表数据
        DeptRespDTO dto = new DeptRespDTO();
        dto.setName(createReqVO.getName());
        dto.setParentId(createReqVO.getDeptId());
        dto.setStatus(0);
        dto.setType(1);

        deptApi.saveDept(dto);

        // 插入
        DeliveryPickUpStoreDO deliveryPickUpStore = DeliveryPickUpStoreConvert.INSTANCE.convert(createReqVO);
        deliveryPickUpStore.setCreateTime(LocalDateTime.now());

        deliveryPickUpStore.setDeptId(dto.getId());

        String[] split = createReqVO.getLnglat().split(",");
        deliveryPickUpStore.setLatitude(Double.parseDouble(split[0]));
        deliveryPickUpStore.setLongitude(Double.parseDouble(split[1]));
        deliveryPickUpStoreMapper.insert(deliveryPickUpStore);

        if (CollectionUtil.isNotEmpty(createReqVO.getImageDOList())){
            //存入门店证件数据
            List<DeliveryPickUpStoreImageDO> imageDOS = DeliveryPickUpStoreImageConvert.INSTANCE.convertList(createReqVO.getImageDOList());
            imageDOS.forEach(x -> {
                x.setStoreId(deliveryPickUpStore.getId());

                x.setCreateTime(LocalDateTime.now());

            });
            deliveryPickUpStoreImageMapper.insertBatch(imageDOS);
        }

        // 返回
        return deliveryPickUpStore.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeliveryPickUpStore(DeliveryPickUpStoreUpdateReqVO updateReqVO) {
        // 校验存在
        validateDeliveryPickUpStoreExists(updateReqVO.getId());
        // 更新
        DeliveryPickUpStoreDO updateObj = DeliveryPickUpStoreConvert.INSTANCE.convert(updateReqVO);
        if (StringUtils.isNotEmpty(updateObj.getLnglat())) {
            String[] split = updateObj.getLnglat().split(",");
            updateObj.setLatitude(Double.parseDouble(split[0]));
            updateObj.setLatitude(Double.parseDouble(split[1]));
        }
        deliveryPickUpStoreMapper.updateById(updateObj);
        if (CollectionUtil.isNotEmpty(updateReqVO.getImageDOList())){
            //存入门店证件数据
            List<DeliveryPickUpStoreImageDO> imageDOS = DeliveryPickUpStoreImageConvert.INSTANCE.convertList(updateReqVO.getImageDOList());
            deliveryPickUpStoreImageMapper.updateBatch(imageDOS);
        }
    }

    @Override
    public void deleteDeliveryPickUpStore(Long id) {
        // 校验存在
        validateDeliveryPickUpStoreExists(id);
        // 删除
        deliveryPickUpStoreMapper.deleteById(id);
    }

    private void validateDeliveryPickUpStoreExists(Long id) {
        if (deliveryPickUpStoreMapper.selectById(id) == null) {
            throw exception(PICK_UP_STORE_NOT_EXISTS);
        }
    }

    @Override
    public DeliveryPickUpStoreDO getDeliveryPickUpStore(Long id) {
        LambdaQueryWrapperX<DeliveryPickUpStoreImageDO> wrapper = new LambdaQueryWrapperX<>();
        wrapper.eq(DeliveryPickUpStoreImageDO ::getStoreId, id );
        // 门店证件信息
        List<DeliveryPickUpStoreImageDO> doList = deliveryPickUpStoreImageMapper.selectList(wrapper);
        // 查询门店信息
        DeliveryPickUpStoreDO storeDO = deliveryPickUpStoreMapper.selectById(id);
        storeDO.setImageDOList(DeliveryPickUpStoreImageConvert.INSTANCE.convertList1(doList));

        return storeDO;
    }

    @Override
    public List<DeliveryPickUpStoreDO> getDeliveryPickUpStoreList(Collection<Long> ids) {
        return deliveryPickUpStoreMapper.selectBatchIds(ids);
    }

    @Override
    public List<DeliveryPickUpStoreDO> getDeliveryPickUpStoreList() {
        return deliveryPickUpStoreMapper.selectList();
    }

    @Override
    public PageResult<DeliveryPickUpStoreDO> getDeliveryPickUpStorePage(DeliveryPickUpStorePageReqVO pageReqVO) {
        return deliveryPickUpStoreMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DeliveryPickUpStoreDO> getDeliveryPickUpStoreListByStatus(Integer status) {
        return deliveryPickUpStoreMapper.selectListByStatus(status);
    }

    @Override
    public List<AppDeliveryPickUpStoreRespVO> getDeliveryPickUpStoreListByStatus(Integer status, String lngLat) {
                List<DeliveryPickUpStoreDO> storeListByStatus = deliveryPickUpStoreMapper.selectListByStatus(CommonStatusEnum.ENABLE.getStatus());
                if(lngLat.split(",").length == 2){
                    Double xX = Double.valueOf(lngLat.split(",")[0]);
                    Double yY = Double.valueOf(lngLat.split(",")[1]);
                    return  DeliveryPickUpStoreConvert.INSTANCE.convertList(storeListByStatus, xX, yY);
                }
                return BeanUtils.toBean(storeListByStatus,AppDeliveryPickUpStoreRespVO.class);
    }

}
